enum Direction {
    UP, DOWN, LEFT, RIGHT
}

class SpiralMatrixBuilder {

    int[][] buildMatrixOfSize(int inputNumber) {
        if (inputNumber <= 0) {
            return new int[][]{};
        }

        int[][] results = new int[inputNumber][inputNumber];

        int step = 1;
        int maxStep = inputNumber * inputNumber;

        fillNumber(results, Direction.RIGHT, step, maxStep, 0, 0);

        return results;
    }

    private void fillNumber(int[][] matrix, Direction direct, int step, int maxStep, int x, int y) {
        if (matrix[x][y] == 0){
            matrix[x][y] = step;
            step++;
        }

        if (step > maxStep) {
            return;
        }

        switch (direct) {
            case RIGHT:
                if (y < matrix[x].length - 1 && matrix[x][y + 1] == 0) {
                    y++;
                } else {
                    direct = Direction.DOWN;
                }
                break;
            case UP:
                if (x > 0 && matrix[x - 1][y] == 0) {
                    x--;
                } else {
                    direct = Direction.RIGHT;
                }
                break;
            case DOWN:
                if (x < matrix.length - 1 && matrix[x + 1][y] == 0) {
                    x++;
                } else {
                    direct = Direction.LEFT;
                }
                break;
            case LEFT:
                if (y > 0 && matrix[x][y - 1] == 0) {
                    y--;
                } else {
                    direct = Direction.UP;
                }
                break;
            default:
                break;
        }

        fillNumber(matrix, direct, step, maxStep, x, y);
    }
}